﻿using Microsoft.AspNetCore.DataProtection.KeyManagement;
using MyJWT;
using Org.BouncyCastle.Asn1.Ocsp;
using System.Linq;

namespace DataTransmissionDemo.Middleware
{
    public class CheckAuthMiddleware
    {
        private readonly RequestDelegate _next;

        public CheckAuthMiddleware(RequestDelegate next)
        {
            _next = next;
            this._next = next;
        }

        #region key

        string publicKey = @"MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAs4nj5hgCQ/THG6NcOFs6/s9HFDbSlIOrWgkFgiPyxQmdjJpH2klJqfaspPcVUEmWh3lAtIJ7CRCMQMwDyqmhXcSl8QQOCl7329UNi+yYV0I4jSK/VLGeUYNOBjSlWVz7CKNUQUDAzbHJWVBf+FbKYMNA68TWHN0xHAQsq4HF4ZppAzgI6vvDqU6W9cCTfY549Davju6pXaqdvJ7ws9K+VLNKJrZuMEOeCEpE5+lidHl46FmCbAhxSzoIA9jIplEUblsmdK9tK2RXAXZJLjx59DlYJ/J8h31ejhQm9JjHiMTxS+TB/TzpcVEN2uuVBsH9MqZSt6RO7OA0Je12IAzaQQIDAQAB";
        #endregion

        public async Task Invoke(HttpContext context)
        {
            if (!context.Request.Headers.ContainsKey("MyAuthToken"))
            {
                await _next.Invoke(context);
                return;
            }
            var token = context.Request.Headers["MyAuthToken"].ToString();
            if (string.IsNullOrEmpty(token))
            {
                await _next.Invoke(context);
                return;
            }
            var result = Utils.SignCheck(token, publicKey);
            if (result.isSuccess)
            {
                var data = result.payload.Data;
                context.Items.TryAdd("UserId", data);
            }
            await _next.Invoke(context);
        }
    }

    public static class CheckAuthExtension
    {
        public static IApplicationBuilder UseCheckAuth(this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<CheckAuthMiddleware>();
        }
    }
}
